#pragma once
#include <iostream>
#include <unordered_map>
#include <string>
#include<stdio.h>
#include <fstream>
#include "log.hpp"
namespace dict_ns
{
    const std::string defaultpath = "./dect.txt";
    const std::string sep = ": ";
    class dict
    {
    private:
        bool load()
        {
            // happy: 快乐的
            std::ifstream in(_dict_conf_filepath);
            if (!in.is_open())
            {
                LOG(FATAL, "open %s error\n", _dict_conf_filepath.c_str());
                return false;
            }
            std::string line;
            while (std::getline(in, line))
            {
                if (line.empty())
                    continue;
                auto pos = line.find(sep);
                if (pos == std::string::npos)
                    continue;
                std::string word = line.substr(0, pos);
                if (word.empty())
                    continue;
                std::string chinese = line.substr(pos + sep.size());
                if (chinese.empty())
                    continue;
                LOG(DEBUG, "load info, %s : %s \n", word.c_str(), chinese.c_str());
                _dict.insert(std::make_pair(word, chinese));
            }
            in.close();
            LOG(DEBUG, "load %s success \n", _dict_conf_filepath.c_str());
            return true;
        }

    public:
        dict(const std::string &path = defaultpath)
            : _dict_conf_filepath(path)
        {
            std::cout << "1" << std::endl;
            load(); // 将磁盘数据加载到内存中
        }
        std::string translate(const std::string &word, bool &ok)
        {
            ok = true;
            auto iter = _dict.find(word);
            if (iter == _dict.end())
            {
                ok = false;
                return "未找到";
            }
            return iter->second;
        }
        ~dict()
        {
        }

    private:
        std::unordered_map<std::string, std::string> _dict; // 字典数据结构
        std::string _dict_conf_filepath;                    // 字典数据路径
    };
}